package com.wj.blog.controller;

import com.wj.blog.enums.ResultEnum;
import com.wj.blog.pojo.User;
import com.wj.blog.service.UserService;
import com.wj.blog.utils.Page;
import com.wj.blog.utils.Result;
import com.wj.blog.utils.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * Author:   wj
 * Date:     2020/4/17 20:02
 * Description: 用户接口
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/save")
    public Result<Object> save(@RequestBody User user){
        userService.save(user);
        return new Result<>("添加成功");
    }

    @DeleteMapping("/{id}")
    public Result<Object> delete(@PathVariable Integer id){
        userService.delete(id);
        return new Result<>("删除成功");
    }

    @PutMapping("/update")
    public Result<Object> update(@RequestBody User user){
        userService.update(user);
        return new Result<>("更新成功");
    }

    @PutMapping("/updateInfo")
    public Result<Object> updateInfo(@RequestBody User user){
        userService.updateInfo(user);
        return new Result<>("更新成功");
    }
    @PostMapping("getByPage")
    public Result<Object> getByPage(@RequestBody Page<User> page){
        //对排序列进行验证，防止sql 注入
        String sortColumn = page.getSortColumn();
        if (StringUtils.isNotBlank(sortColumn)) {
            // 排序列不为空
            String[] sortColumns = {"sex", "created_time", "update_time"};
            List<String> sortList = Arrays.asList(sortColumns);
            if (!sortList.contains(sortColumn.toLowerCase())) {
                return new Result<>(ResultEnum.PARAMS_ERROR.getCode(), "排序参数不合法！");
            }
        }
       Page<List<User>> list= userService.getByPage(page);
       return new Result<>(list);
    }
    @GetMapping("{id}")
    public Result<Object> getById(@PathVariable Integer id){

        return userService.getById(id);
    }
}
